package com.freedom.admin.application.service.query;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.freedom.admin.application.converter.UserConverter;
import com.freedom.admin.domain.repository.PermissionRepository;
import com.freedom.admin.domain.repository.SysUserRepository;
import com.freedom.admin.infrastructure.persistence.pojo.bo.UserAuthBO;
import com.freedom.admin.infrastructure.persistence.pojo.bo.UserBO;
import com.freedom.admin.infrastructure.persistence.pojo.bo.UserFormBO;
import com.freedom.admin.infrastructure.persistence.pojo.form.UserForm;
import com.freedom.admin.infrastructure.persistence.pojo.query.UserPageQuery;
import com.freedom.admin.infrastructure.persistence.pojo.vo.user.LoginUserVO;
import com.freedom.admin.infrastructure.persistence.pojo.vo.user.UserVO;
import com.freedom.admin.api.pojo.dto.UserAuthDTO;
import com.freedom.common.security.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
@RequiredArgsConstructor
public class UserQueryService {

    private final SysUserRepository sysUserRepository;

    private final PermissionRepository permissionRepository;

    private final UserConverter userConverter;

    public Page<UserVO> listUserPages(UserPageQuery queryParams) {
        Page<UserBO> userBOPage = sysUserRepository.listUserPages(queryParams);
        return userConverter.toPageVO(userBOPage);
    }

    public UserForm findUserFormData(Integer userId) {
        UserFormBO userFormBO = sysUserRepository.findUserFormData(userId);
        return userConverter.poToForm(userFormBO);
    }

    public LoginUserVO getLoginUserInfo() {
        UserBO userBO = sysUserRepository.findById(SecurityUtils.getUserId());
        LoginUserVO loginUserVO = userConverter.toLoginUserVO(userBO);

        Set<String> roleCodeList = SecurityUtils.getRoles();
        loginUserVO.setRoles(roleCodeList);

        List<String> btnPermList = permissionRepository.findByRoleCodes(roleCodeList);
        loginUserVO.setPerms(btnPermList);

        return loginUserVO;
    }

    public UserAuthDTO findUserByUsername(String username) {
        UserAuthBO userAuthBO = sysUserRepository.getAuthInfoByUsername(username);
        return userConverter.toUserAuthDTO(userAuthBO);
    }
}
